package com.atguigu.gulimall.ware.listener;

import com.atguigu.gulimall.common.to.OrderTo;
import com.atguigu.gulimall.common.to.mq.StockLockedTo;
import com.atguigu.gulimall.ware.config.RabbitConfig;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@RabbitListener(queues = RabbitConfig.DEAD_QUEUE)
@Component
public class RollBackWareSkuListener {

    @Autowired
    private WareSkuService wareSkuService;

    @RabbitHandler
    public void handleStockLOckRelease(StockLockedTo lockedTo, Message message, Channel channel) throws IOException {
        // 如果 wareSkuService.handleStockLOckRelease(lockedTo);没有错误，表示ok，否则拒绝该消息
        try {
            wareSkuService.handleStockLOckRelease(lockedTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            // 拒绝后放回队列中
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void OrderCloseNoQuick(OrderTo orderTo, Message message, Channel channel) throws IOException {
        try {
            wareSkuService.OrderCloseNoQuick(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            // 拒绝后放回队列中
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
